from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from .models import DictBiz
from frame_server.serializers import BaseSerializer as BSerializer

# 新增/编辑验证基类
class AddEditValidateBase(BSerializer):
    parentId = serializers.IntegerField(required=False, allow_null=True)
    code = serializers.CharField(max_length=255)
    dictText = serializers.CharField(max_length=255)
    dictValue = serializers.CharField(required=False, allow_null=True, max_length=255)
    sort = serializers.IntegerField()
    isSealed = serializers.IntegerField()
    
    class Meta:
        model = DictBiz

    def validate(self, data):
        if not data.get("parentId") and data.get("dictValue"):
            raise serializers.ValidationError("dictValue不能为空")
        return data
    
    def validate_parentId(self, val):
        if val is None:
            return None
        if not DictBiz.objects.filter(id=val).exists():
            raise serializers.ValidationError("上级字典不存在")
        return DictBiz.objects.only('id').get(id=val)
    
# 新增
class AddValidate(AddEditValidateBase):
    
    class Meta(AddEditValidateBase.Meta):
        exclude = ['id']
        validators = [
            UniqueTogetherValidator(
                queryset=DictBiz.objects.only('dictText','code').all(),
                fields=['dictText','code'],
                message='字典编号不能与字典名称重复'
            )
        ]

# 编辑
class EditValidate(AddEditValidateBase):
    id = serializers.IntegerField()
    
    def validate_id(self, val):
        if not DictBiz.objects.filter(id=val).exists():
            raise serializers.ValidationError("编辑对象不存在")
        return val
    
    class Meta(AddEditValidateBase.Meta):
        fields = '__all__'

    def update(self, instance, validated_data):
        obj = super().update(instance, validated_data)
        DictBiz.objects.filter(parentId=obj).update(code=obj.code)  # 同步更新它的关联数据
        return obj